package com.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.PowerMapper;
import com.mapper.RoleMapper;
import com.pojo.Power;
import com.pojo.Role;
import com.service.PowerService;
import com.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PowerService powerService;
    @Override
    public PageInfo selectRolesByName(Map map) {
        int pageNum = (int)map.get("pageNum");
        PageHelper.startPage(pageNum,2);
        String name = (String)map.get("name");
        List<Role> roles = roleMapper.selectRolesByName(name);
        //根据角色id，查询power权限
        for (int i = 0; i < roles.size(); i++) {
            long id = roles.get(i).getId();
            List<Power> powers = powerService.selectPowersByRole_id(id);
            roles.get(i).setPowers(powers);
        }
        PageInfo pageInfo=new PageInfo(roles);
        return pageInfo;
    }

    @Override
    public Role selectRoleById(long id) {
        return roleMapper.selectRoleById(id);
    }

    @Override
    public int updateRole(Role role) {
        return roleMapper.updateRole(role);
    }

    @Override
    public int insertRole(Role role) {
        return roleMapper.insertRole(role);
    }

    @Override
    public int deleteRoleById(long id) {
        return roleMapper.deleteRoleById(id);
    }

    @Override
    public int resumeRoleById(long id) {
        return roleMapper.resumeRoleById(id);
    }

    @Override
    public List<Role> selectAllRoles() {
        List<Role> roles = roleMapper.selectAllRoles();
        for (int i=0;i<roles.size();i++){
            Role role = roles.get(i);
            List<Power> powers = powerService.selectPowersByRole_id(role.getId());
            role.setPowers(powers);
        }
        return  roles;
    }

    @Override
    public List<Role> selectAllRoleById(long id) {
        return roleMapper.selectByid(id);
    }

    @Override
    public int updateRolePower(long rid, long[] pids) {
        //1.先删除该角色以前具有的权限，根据角色id
         roleMapper.deleteRolePower(rid);
        //2.根据rid pid添加
        for (int i = 0; i < pids.length; i++) {
            roleMapper.addRolePower(rid,pids[i]);
        }
        return 1;
    }
}
